<template>
  <div class="permission-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>权限管理</span>
          <el-button type="primary" @click="handleAddPermission">
            <el-icon><Plus /></el-icon>
            添加权限
          </el-button>
        </div>
      </template>
      
      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :model="searchForm" inline>
          <el-form-item label="权限名称">
            <el-input
              v-model="searchForm.name"
              placeholder="请输入权限名称"
              clearable
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item label="权限类型">
            <el-select v-model="searchForm.type" placeholder="请选择权限类型" clearable>
              <el-option label="用户权限" value="USER" />
              <el-option label="管理权限" value="ADMIN" />
              <el-option label="系统权限" value="SYSTEM" />
            </el-select>
          </el-form-item>
          <el-form-item label="资源">
            <el-input
              v-model="searchForm.resource"
              placeholder="请输入资源名称"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleResetSearch">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 权限列表 -->
      <el-table :data="permissionList" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="权限名称" width="200" />
        <el-table-column prop="code" label="权限编码" width="200" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="permissionType" label="权限类型" width="120">
          <template #default="scope">
            <el-tag :type="getTypeColor(scope.row.permissionType)">
              {{ getTypeName(scope.row.permissionType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="level" label="权限级别" width="120">
          <template #default="scope">
            <el-tag :type="getLevelType(scope.row.level)">
              {{ getLevelName(scope.row.level) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" type="primary" @click="handleEditPermission(scope.row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button size="small" type="danger" @click="handleDeletePermission(scope.row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 编辑权限对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      :title="isEdit ? '编辑权限' : '添加权限'"
      width="600px"
      :close-on-click-modal="false"
      @close="cancelEdit"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editFormRules"
        label-width="100px"
      >
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="editForm.name" placeholder="如：article:read, user:write" />
          <div class="form-tip">建议格式：资源:操作，如 article:read（文章查看）</div>
        </el-form-item>
        <el-form-item label="权限编码" prop="code">
          <el-input v-model="editForm.code" placeholder="如：PERM_ARTICLE_READ" />
          <div class="form-tip">权限编码，建议格式：PERM_资源_操作</div>
        </el-form-item>
        <el-form-item label="权限描述" prop="description">
          <el-input 
            v-model="editForm.description" 
            type="textarea"
            :rows="3"
            placeholder="请输入权限描述" 
          />
        </el-form-item>
        <el-form-item label="权限类型" prop="permissionType">
          <el-select v-model="editForm.permissionType" placeholder="请选择权限类型">
            <el-option label="用户权限" value="USER" />
            <el-option label="管理权限" value="ADMIN" />
            <el-option label="系统权限" value="SYSTEM" />
          </el-select>
          <div class="form-tip">
            用户权限：普通用户可操作<br>
            管理权限：管理员及以上可操作<br>
            系统权限：系统管理员可操作
          </div>
        </el-form-item>
        <el-form-item label="权限级别" prop="level">
          <el-select v-model="editForm.level" placeholder="请选择权限级别">
            <el-option label="游客权限" :value="0" />
            <el-option label="用户权限" :value="1" />
            <el-option label="管理权限" :value="2" />
            <el-option label="系统权限" :value="3" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelEdit">取消</el-button>
          <el-button type="primary" @click="submitEditForm" :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getPermissionList, 
  createPermission, 
  updatePermission, 
  deletePermission
} from '@/api/permission'

// 响应式数据
const loading = ref(false)
const permissionList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 搜索表单
const searchForm = reactive({
  name: '',
  type: '',
  resource: ''
})

// 编辑对话框
const editDialogVisible = ref(false)
const isEdit = ref(false)
const editFormRef = ref()
const submitLoading = ref(false)
const editForm = reactive({
  id: null,
  name: '',
  code: '',
  description: '',
  permissionType: '',
  level: null
})

// 表单验证规则
const editFormRules = {
  name: [
    { required: true, message: '请输入权限名称', trigger: 'blur' },
    { min: 2, max: 100, message: '权限名称长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入权限编码', trigger: 'blur' },
    { min: 2, max: 100, message: '权限编码长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '权限描述不能超过 200 个字符', trigger: 'blur' }
  ],
  permissionType: [
    { required: true, message: '请选择权限类型', trigger: 'change' }
  ],
  level: [
    { required: true, message: '请选择权限级别', trigger: 'change' }
  ]
}

// 获取权限列表
const fetchPermissionList = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      ...searchForm
    }
    const response = await getPermissionList(params)
    if (response.code === 200) {
      permissionList.value = response.data.records
      total.value = response.data.total
    } else {
      ElMessage.error(response.message || '获取权限列表失败')
    }
  } catch (error) {
    console.error('获取权限列表失败:', error)
    ElMessage.error('获取权限列表失败')
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchPermissionList()
}

// 重置搜索
const handleResetSearch = () => {
  searchForm.name = ''
  searchForm.type = ''
  searchForm.resource = ''
  currentPage.value = 1
  fetchPermissionList()
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchPermissionList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchPermissionList()
}

// 添加权限
const handleAddPermission = () => {
  isEdit.value = false
  editForm.id = null
  editForm.name = ''
  editForm.code = ''
  editForm.description = ''
  editForm.permissionType = ''
  editForm.level = null
  editDialogVisible.value = true
}

// 编辑权限
const handleEditPermission = (row) => {
  isEdit.value = true
  editForm.id = row.id
  editForm.name = row.name
  editForm.code = row.code
  editForm.description = row.description
  editForm.permissionType = row.permissionType
  editForm.level = row.level
  editDialogVisible.value = true
}

// 提交表单
const submitEditForm = async () => {
  try {
    await editFormRef.value.validate()
    submitLoading.value = true
    
    const data = {
      name: editForm.name,
      code: editForm.code,
      description: editForm.description,
      permissionType: editForm.permissionType,
      level: editForm.level
    }
    
    let response
    if (isEdit.value) {
      response = await updatePermission(editForm.id, data)
    } else {
      response = await createPermission(data)
    }
    
    if (response.code === 200) {
      ElMessage.success(isEdit.value ? '权限更新成功' : '权限创建成功')
      editDialogVisible.value = false
      fetchPermissionList()
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    console.error('提交表单失败:', error)
    if (error.message) {
      ElMessage.error(error.message)
    }
  } finally {
    submitLoading.value = false
  }
}

// 取消编辑
const cancelEdit = () => {
  editDialogVisible.value = false
  editFormRef.value?.resetFields()
}

// 删除权限
const handleDeletePermission = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除权限 "${row.name}" 吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    const response = await deletePermission(row.id)
    if (response.code === 200) {
      ElMessage.success('权限删除成功')
      fetchPermissionList()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除权限失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 辅助函数
const getTypeColor = (type) => {
  const colors = { 'USER': 'success', 'ADMIN': 'warning', 'SYSTEM': 'danger' }
  return colors[type] || ''
}

const getTypeName = (type) => {
  const names = { 'USER': '用户权限', 'ADMIN': '管理权限', 'SYSTEM': '系统权限' }
  return names[type] || type
}

const getLevelType = (level) => {
  const types = { 0: 'info', 1: '', 2: 'warning', 3: 'danger' }
  return types[level] || ''
}

const getLevelName = (level) => {
  const names = { 0: '游客权限', 1: '用户权限', 2: '管理权限', 3: '系统权限' }
  return names[level] || '未知'
}

const formatDate = (dateString) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleString()
}

// 初始化
onMounted(() => {
  fetchPermissionList()
})
</script>

<style scoped>
.permission-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-area {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: right;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
  line-height: 1.4;
}
</style>